﻿using BusinessLayer;
using BusinessLayer.VDataEntities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
using TrialManagementTool.Helper;
using TrialManagmentTool.Helper;

namespace TrialManagementTool.Auth
{
    public class Authenticate
    {
        static string sToken = ConfigurationManager.AppSettings["Token"].ToString();
        static string sCorpID = ConfigurationManager.AppSettings["CorpID"].ToString();
        static string sEncodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"].ToString();
        static string code;
        public static string CheckWeixinUserID()
        {
            string userID = string.Empty;

            if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "userid"] == null)
            {
                WeChatHelper wechatHelp = new WeChatHelper();
                string token = wechatHelp.GetToken();
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
   sCorpID, System.Web.HttpUtility.UrlEncode(ConfigurationManager.AppSettings["WeixinBaseUrl"] + HttpContext.Current.Request.RawUrl), "snsapi_base", "State");

                if (HttpContext.Current.Request["code"] != null)
                {
                    if (code != HttpContext.Current.Request["code"].ToString())
                    {
                        code = HttpContext.Current.Request["code"].ToString();

                        string userurl = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", token, HttpContext.Current.Request.QueryString["code"]);
                        HttpWebRequest hwr = WebRequest.Create(userurl) as HttpWebRequest;
                        hwr.Method = "POST";
                        hwr.ContentType = "application/x-www-form-urlencoded";
                        var result = hwr.GetResponse() as HttpWebResponse;
                        StreamReader reader = new StreamReader(result.GetResponseStream(), Encoding.UTF8);
                        string content = reader.ReadToEnd();
                        reader.Close();
                        reader.Dispose();
                        var obj = JsonConvert.DeserializeObject(content) as JObject;
                        LogHelper.Info("Get UserInfo from wechat:" + obj.ToString());

                        if (obj["UserId"] == null)
                        {
                            return userID;
                        }
                        else
                        {
                            VPromoter validatePromoter = PromoterBusiness.ValidatePromoter(obj["UserId"].ToString());
                            if (validatePromoter != null)
                            {
                                UserHelper.SaveUserInfoToCookie(JsonConvert.SerializeObject(validatePromoter));
                                //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "userid", DateTime.Now,
                                //    DateTime.Now.AddDays(5), true, obj["UserId"].ToString());
                                //string userinfoticket = FormsAuthentication.Encrypt(ticket);
                                //添加userid到cookie
                                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName + "userid", obj["UserId"].ToString());
                                cookie.HttpOnly = true;
                                cookie.Expires = DateTime.Now.AddHours(20);
                                HttpContext.Current.Response.Cookies.Add(cookie);
                                userID = obj["UserId"].ToString();
                            }
                            else
                            {
                                LogHelper.Info(string.Format("{0} is not in the promoter table", obj["UserId"].ToString()));
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(5000);
                    }
                }
                else
                {
                    HttpContext.Current.Response.Redirect(url);
                }
            }
            else
            {
                HttpCookie aCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "userid"];
                if (aCookie != null && !string.IsNullOrEmpty(aCookie.Value))
                {
                    userID = aCookie.Value;
                    
                    //try
                    //{
                    //    FormsAuthenticationTicket tit = FormsAuthentication.Decrypt(aCookie.Value);
                    //    userID = tit.UserData;
                    //}
                    //catch
                    //{
                    //    userID = string.Empty;
                    //}
                }
                return userID;
            }
            return userID;
        }
    }
}